<?php

namespace app\controller;

use app\BaseController;
use app\message;
use app\model\CluePerson;
use app\model\OrderEnterpriseCertificateRegister;
use app\model\OrderEnterpriseExchange;
use app\model\OrderPersonCertificateRegister;
use app\model\PublicCollect;
use app\model\PublicSaleRule;
use app\model\SystemCertificate;
use app\model\SystemOperateLog;
use app\model\UnitInfo;
use app\model\User;
use app\model\UserOrganization;
use app\Request;
use app\service\Clue;
use app\service\Excel;
use app\stateData;
use app\validate\Certificate;
use app\validate\PublicValidate;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;
use think\facade\Validate;
use function Symfony\Component\VarDumper\Dumper\esc;

class Publicity extends BaseController
{

    /**
     * 获取部门下所有人员
     * @param Request $request
     * @param UserOrganization $userOrganization
     * @param User $user
     * @return false|string
     */
    public function getDepartmentUserList(Request $request, UserOrganization $userOrganization, User $user)
    {
        $department_id = $request->get ('department_id');
        if (!$department_id) {
            ReJson (message::$ERROR_CODE, message::$DEPARTMENT_ID_NULL);
        }
        $department_ids = $userOrganization->getDataRangeDepartmentList ([], $department_id);
        $department_ids[] = (int)$department_id;
        $list = $user->getDepartmentUserList ($department_ids);
        return ReJson (message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $list);
    }
    /**
     * 公示栏
     */

    //获取公示栏人才列表
    public function getPersonList(
        Request                        $request,
        OrderPersonCertificateRegister $personCerReg,
        \app\service\Publicity         $publicity,
        \app\service\Certificate       $certificate,
        SystemCertificate              $certificateModel
    )
    {
        $uid = $request->param ('user_login_id');
        $param = $request->get ();
        $sort = $request->get ('sort') ?: 0;
        /**
         * 上方条件为字符串 高级查询为数组
         * 前期写的时候没有or条件 后期没时间修改
         * 只能model层判断where类型 array使用where查询 string使用whereRaw查询
         */
        $whereOr = '';
        $certificate_leixing = isset($param['condition_leixing'])?explode (',',$param['condition_leixing']):''; //主证书
        $certificate_leibie = isset($param['condition_leibie'])?explode (',',$param['condition_leibie']):'';//证书详细分类
        $seDate = $param['se_date'] ?? '';

        /**
         * 处理条件
         */
        if ($certificate_leixing && $certificate_leixing[0]){
            foreach ($certificate_leixing as $leixing) {
                /**
                 * 去掉前段传值的 * “类“
                 */
                $leixing = str_replace ('类','',$leixing);

                $cid = $certificateModel->getWhereCertificateIdModel ($leixing);

                //判断证书是否存在
                if (!$cid){
                    return ReJson (message::$ERROR_CODE,message::$SELECT_CERTIFICATE_ERR);
                }

                if (!$whereOr){
                    $whereOr .= "( certificate_leixing =".$cid;
                }else{
                    $whereOr .= " OR certificate_leixing =".$cid;
                }
            }
            $whereOr.= ')'; //拼接结束
        }

        if ($certificate_leibie && $certificate_leibie[0]){
            foreach ($certificate_leibie as $leibie) {
                /**
                 * 查询是否为组合条件（、）分割
                 */
                if (strpos ($leibie,'、')){
                    $leibieArr = explode ('、',$leibie);
                    $leibielenght = count ($leibieArr);
                    /**
                     * 长度最大为3  1为类别 2为等级 3为专业
                     */
                    if ($leibielenght == 3){
                        $cid = $certificateModel->getWhereCertificateIdModel ($leibieArr[0]);
                        $cid2 = $certificateModel->getWhereCertificateIdModel ($leibieArr[1],$cid);
                        $cid3 = $certificateModel->getWhereCertificateIdModel ($leibieArr[2],$cid2);
                        //判断证书是否存在
                        if (!$cid || !$cid2 || !$cid3){
                            return ReJson (message::$ERROR_CODE,message::$SELECT_CERTIFICATE_ERR);
                        }
                        if (!$whereOr){
                            $whereOr .= " certificate_leibie = ".$cid.' and certificate_dengji = '.$cid2.' and certificate_zhuanye='.$cid3;
                        }else{
                            $whereOr .= " and certificate_leibie =".$cid.' and certificate_dengji = '.$cid2.' and certificate_zhuanye='.$cid3;
                        }
                    }else if ($leibielenght == 2){
                        $cid = $certificateModel->getWhereCertificateIdModel ($leibieArr[0]);
                        $cid2 = $certificateModel->getWhereCertificateIdModel ($leibieArr[1],$cid);
                        //判断证书是否存在
                        if (!$cid || !$cid2){
                            return ReJson (message::$ERROR_CODE,message::$SELECT_CERTIFICATE_ERR);
                        }
                        if (!$whereOr){
                            $whereOr .= " certificate_leibie = ".$cid.' and certificate_dengji = '.$cid2;
                        }else{
                            $whereOr .= " and certificate_leibie =".$cid.' and certificate_dengji = '.$cid2;
                        }
                    }else{
                        $cid = $certificateModel->getWhereCertificateIdModel ($leibieArr[0]);
                        //判断证书是否存在
                        if (!$cid){
                            return ReJson (message::$ERROR_CODE,message::$SELECT_CERTIFICATE_ERR);
                        }
                        if (!$whereOr){
                            $whereOr .= " certificate_leibie = ".$cid;
                        }else{
                            $whereOr .= " and certificate_leibie =".$cid;
                        }
                    }
                }else{
                    $cid = $certificateModel->getWhereCertificateIdModel ($leibie);
                    if (!$whereOr){
                        $whereOr .= " certificate_leibie =".$cid;
                    }else{
                        $whereOr .= " and certificate_leibie =".$cid;
                    }
                }
            }
        }
        $whereDate = '';

        if ($seDate == 1){
            $start_create_date = date('Y-m-d').' 00:00:00';
            $end_create_date = date('Y-m-d').' 23:59:59';
            $whereDate = 'create_date between "'.$start_create_date.'" and "'.$end_create_date.'"';
        }elseif ($seDate == 2){ //近三天
            $start_create_date = date('Y-m-d',time ()-86400*2).' 00:00:00';
            $end_create_date = date('Y-m-d').' 23:59:59';
            $whereDate = 'create_date between "'.$start_create_date.'" and "'.$end_create_date.'"';
        }elseif ($seDate == 3){//一周
            $start_create_date = date('Y-m-d',time ()-86400*6).' 00:00:00';
            $end_create_date = date('Y-m-d').' 23:59:59';
            $whereDate = 'create_date between "'.$start_create_date.'" and "'.$end_create_date.'"';
        }elseif ($seDate == 4){//当月
            $start_create_date = date('Y-m-01').' 00:00:00';
            $end_create_date = date('Y-m-d').' 23:59:59';
            $whereDate = 'create_date between "'.$start_create_date.'" and "'.$end_create_date.'"';
        }

        if(!empty($param['start_date'])){
            $whereDate = '';
        }

        $where = $this->extracted ($request, $certificate, $certificateModel);
        //区间收证价
        if (!empty($param['contract_price_end'])) {
            $where[] = ['contract_price', 'between', [$param['contract_price_start'], $param['contract_price_end']]];
        }

        //人员归属查询
        if (!empty($param['submit_id'])) { //前段传值 搜索用户
            $where[] = ['get_uid', '=', $param['submit_id']];
        } else {
            //公司
            if (!empty($param['org'])) {
                $userOrganization = new UserOrganization();
                $user = new User();

                //查询这个公司下面所有公司->人员
                $department_id = $request->get ('org');
                if (!$department_id) {
                    ReJson (message::$ERROR_CODE, message::$DEPARTMENT_ID_NULL);
                }

                $department_ids = $userOrganization->getDataRangeDepartmentList ([], $department_id);
                $department_ids[] = (int)$department_id;

                $idArr = $user->getDepartmentUserIdList ($department_ids);

                if (empty($idArr)) {
                    $where[] = ['get_uid', 'in', 0];
                } else {
                    $where[] = ['get_uid', 'in', $idArr];
                }
            }
        }

        if ($sort == 1) {
            $sort = "create_date ASC";
        } else {
            $sort = "create_date DESC";
        }

        $gs_data = $personCerReg->getWhereStatus (1, 1, $where, $whereOr,$whereDate,$sort);
        $gs = $publicity->setPublicityPersonData ($gs_data, $uid);

        $wb_data = $personCerReg->getWhereStatus (1, 2, $where, $whereOr,$whereDate,$sort);
        $wb = $publicity->setPublicityPersonData ($wb_data, $uid);

        if ($param['cycle'] || $param['cycle'] === 0 || $param['cycle'] === '0') {

            foreach ($wb as $k => &$item) {

                $flag = false;
                if (empty($item['arr']['cycle']['id'])) {
                    unset($wb[$k]);
                    continue;
                }
                foreach ($item['arr']['cycle']['id'] as $value) {

                    if ($value != $param['cycle']) {
                        continue;
                    }
                    $flag = true;
                }
                if (!$flag) {
                    unset($wb[$k]);
                }

                //特价证书未通过 则不显示
//                if ($item['certificate_characteristic_status'] != 1){
//                    $item['certificate_characteristic'] = [
//                        'id'=>'',
//                        'text'=>''
//                    ];
//                }
            }

            foreach ($gs as $ks => &$gsItem) {

                $flag = false;
                if (empty($gsItem['arr']['cycle']['id'])) {
                    unset($gs[$ks]);
                    continue;
                }
                foreach ($gsItem['arr']['cycle']['id'] as $value) {
                    if ($value != $param['cycle']) {
                        continue;
                    }
                    $flag = true;
                }
                if (!$flag) {
                    unset($gs[$ks]);
                }
            }
        }
        return ReJson (message::$SUCC_CODE, message::$SUCC_SELECT_DATA, [
            'gsCertificateData' => $gs,
            'wbCertificateData' => $wb
        ]);
    }

    //新建人才
    public function addPublicPerson(
        Request                        $request,
        \app\service\Certificate       $certificate,
        OrderPersonCertificateRegister $certificateRegister,
        \app\service\Certificate       $certificateSer,
        User                           $user,
        SystemOperateLog               $systemOperateLogModel
    )
    {
        $uid = $request->post ('user_login_id');

        try {
            //拆分证书
            $param = $certificateSer->splitCer ($request->post ());
            $param['certificate_code'] = $certificate->CertificateCodeCreate ();
            $param['status'] = 1;
            $param['submit_id'] = $uid;

            Validate (Certificate::class)->scene ('publicAddPerson')->check ($param);
            if (isset($param['cycle'])) {
                $param['cycle'] = implode (',', $param['cycle']);
            }

            if (!$param['get_uid']) {
                $param['get_uid'] = $param['submit_id'];
                $param['get_org'] = $user->userInfo ($param['get_uid'])['department_id']['id'];
            }

            $systemOperateLogModel->addOperate ($uid, message::$GSL, '公示栏新建人才证书');
            $certificateRegister->addCerRegisterModel ($param);
        } catch (\Exception|ValidateException $e) {
            return ReJson (message::$ERROR_CODE, $e->getMessage ());
        }
        return ReJson (message::$SUCC_CODE, message::$SUCC_INSERT_DATA);
    }

    //收藏人才注册证书订单
    public function addCollectCer(
        Request                        $request,
        PublicCollect                  $collect,
        \app\service\Publicity         $publicity,
        OrderPersonCertificateRegister $personCertificateRegister,
        SystemOperateLog               $systemOperateLogModel
    )
    {

        $param = $request->post ();
        $uid = $request->post ('user_login_id');

        try {
            $param['uid'] = $uid;
            //通过人才id查询该人才证书详细信息
            $personData = $personCertificateRegister->getIdDetails ($param['order_person_id']);

            Validate (PublicValidate::class)->check ($param);

            //判断是否满足销售规则
            if (!$publicity->determineRule ($personData['certificate_id'], $uid)) {
                return ReJson (message::$ERROR_CODE, message::$ERR_ACC_SC_POWER);
            }

            //盘算是否被收藏
            if ($collect->getOrderPersonIdData ($param['order_person_id'])) {
                return ReJson (message::$ERROR_CODE, message::$ERR_PERSON_ORDER_EXIST);
            }

            $systemOperateLogModel->addOperate ($uid, message::$GSL, '公示栏收藏人才证书:'.$personData['certificate_code']);
            $collect->addData ($param);
        } catch (ValidateException|\Exception $e) {
            return ReJson (message::$ERROR_CODE, $e->getMessage ());
        }
        return ReJson (message::$SUCC_CODE, message::$SUCC_COLLECT);
    }

    //取消收藏人才注册证书订单
    public function delCollectCer(Request $request, PublicCollect $collect, SystemOperateLog $systemOperateLogModel,OrderPersonCertificateRegister $personCertificateRegister)
    {

        $param = $request->post ();
        $uid = $request->post ('user_login_id');

        try {
            $param['uid'] = $uid;
            //通过人才id查询该人才证书详细信息
            $personData = $personCertificateRegister->getIdDetails ($param['order_person_id']);

            Validate (PublicValidate::class)->check ($param);

            $systemOperateLogModel->addOperate ($uid, message::$GSL, '公示栏取消收藏人才证书:'.$personData['certificate_code']);
            $collect->delData ($param);
        } catch (ValidateException|\Exception $e) {
            return ReJson (message::$ERROR_CODE, $e->getMessage ());
        }
        return ReJson (message::$SUCC_CODE, message::$SUCC_CANCELLATION_COLLECT);
    }

    //删除人才证书
    public function delPersonCertificate(Request $request, OrderPersonCertificateRegister $certificateRegister, SystemOperateLog $systemOperateLogModel)
    {
        $id = $request->post ('id');
        $uid = $request->post ('user_login_id');
        if (empty($id)) {
            return ReJson (message::$ERROR_CODE, '请选择要删除的信息');
        }
        $ids = explode (',', $id);
//        foreach($ids as $key => $item){
//            $personData = $certificateRegister->getIdDetails($item);
//            if ((!$personData) || ($personData['submit_id'] != $request->param ('user_login_id'))){
//                unset($ids[$key]);
//            }
//        }
//        if(!$ids){
//            return ReJson (message::$ERROR_CODE,message::$ERR_NO_POWER_DEL_CAERTIFICATE);
//        }
//        $id = implode(',',$ids);
        //先查询证书
        $order = $certificateRegister->getIdDetails ($id);
        $systemOperateLogModel->addOperate ($uid, message::$GSL, '公示栏删除人才证书:' . $order['certificate_code']);
        $certificateRegister->delId ($ids);

        return ReJson (message::$SUCC_CODE, message::$SUCC_DATELE_DATA);
    }

    //修改人才证书
    public function editPersonCertificate(
        Request                        $request,
        OrderPersonCertificateRegister $certificateRegister,
        \app\service\Certificate       $certificateSer,
        SystemOperateLog               $systemOperateLogModel
    )
    {
        $id = $request->post ('id');

        $uid = $request->post ('user_login_id');

        //拆分证书
        $param = $certificateSer->splitCer ($request->post ());

        try {
            if (empty($id)) return ReJson (message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

            if (!empty($param['cycle'])) {
                $param['cycle'] = implode (',', $param['cycle']);
            }
            Validate (Certificate::class)->scene ('publicAddPerson')->check ($param);

            $personData = $certificateRegister->getIdDetails ($id);

            if (!$personData) {
                return ReJson (message::$ERROR_CODE, message::$ERR_NO_POWER_SAVE);
            }

            if ($personData['get_uid']['id'] != $uid) {
                return ReJson (message::$ERROR_CODE, message::$ERR_NO_POWER_SAVE);
            }

            //编辑时候替换时间
            $param['create_date'] = date ('Y-m-d,H:i:s');
            $order = $certificateRegister->getIdDetails ($param['id']);

            $systemOperateLogModel->addOperate ($uid, message::$GSL, '公示栏修改人才证书：' . $order['certificate_code']);

            $certificateRegister->editId ($param);
        } catch (\Exception|ValidateException $e) {
            return ReJson (message::$ERROR_CODE, $e->getMessage ());
        }
        return ReJson (message::$SUCC_CODE, message::$SUCC_UPDATE);
    }

    //获取销售规则列表
    public function getRuleList(
        PublicSaleRule           $saleRule,
        \app\service\Certificate $certificate,
        User                     $user,
        UserOrganization         $org,
        \app\service\Certificate $certificateSer
    )
    {
        $result = $saleRule->getRuleModel ();
        foreach ($result as &$item) {
            //处理星期
//            $item['week'] = intTostr($item['week']);
            $item['weeks'] = intTostr ($item['week']);
            $item['start_dates'] = [$item['start_date'], $item['end_date']];

            if (!empty($item['uid'])) {
                $users = $user->getIdUserRandInfo ($item['uid']);
                $item['user'] = '';
                foreach ($users as $iValue) {
                    $item['user'] .= $iValue['nickname'] . '、';
                }
            }

            if (!empty($item['org_id'])) {
                $orgs = $org->getOrgInNameModel ($item['org_id']);
                $item['org'] = '';
                foreach ($orgs as $iValue) {
                    $item['org'] .= $iValue['title'] . '、';
                }
            }

            //证书转一维数组
            $item['certificate_id'] = explode (',', $item['certificate_id']);
            $item = $certificateSer->getCertificateInfo ($item);

        }
        return ReJson (
            message::$SUCC_CODE,
            message::$SUCC_SELECT_DATA,
            $result
        );
    }


    //新建销售规则
    public function personSaleRule(
        Request                  $request,
        PublicSaleRule           $saleRule,
        \app\service\Certificate $certificateSer,
        SystemOperateLog         $systemOperateLogModel
    )
    {
        //拆分证书
        $param = $certificateSer->splitCer ($request->post ());
        $uid = $request->post ('user_login_id');
        try {
            $param['start_date'] = $param['start_dates'][0] ?? 0;
            $param['end_date'] = $param['start_dates'][1] ?? 0;

            Validate (PublicValidate::class)->scene ('addRule')->check ($param);

            $systemOperateLogModel->addOperate ($uid, message::$GSL, '公示栏新建销售规则');
            $saleRule->addRule ($param);
        } catch (\Exception|ValidateException $e) {
            return ReJson (message::$ERROR_CODE, $e->getMessage ());
        }
        return ReJson (message::$SUCC_CODE, message::$SUCC_INSERT_DATA);
    }

    //删除销售规则
    public function delRule(Request $request, PublicSaleRule $saleRule, SystemOperateLog $systemOperateLogModel)
    {
        $id = $request->post ('id');
        $uid = $request->post ('user_login_id');

        if (empty($id)) return ReJson (message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        $systemOperateLogModel->addOperate ($uid, message::$GSL, '公示栏删除销售规则');
        $saleRule->delRuleModel ($id);

        return ReJson (message::$SUCC_CODE, message::$SUCC_DATELE_DATA);
    }

    //编辑销售规则
    public function editRule(
        Request                  $request,
        PublicSaleRule           $saleRule,
        \app\service\Certificate $certificateSer,
        SystemOperateLog         $systemOperateLogModel
    )
    {
        $param = $certificateSer->splitCer ($request->post ());
        $uid = $request->post ('user_login_id');

        if (empty($param['id'])) return ReJson (message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        try {
            $param['start_date'] = $param['start_dates'][0];
            $param['end_date'] = $param['start_dates'][1];

            Validate (PublicValidate::class)->scene ('addRule')->check ($param);

            $systemOperateLogModel->addOperate ($uid, message::$GSL, '公示栏编辑销售规则');
            $saleRule->editRuleModel ($param);
        } catch (\Exception|ValidateException $e) {
            return ReJson (message::$ERROR_CODE, $e->getMessage ());
        }
        return ReJson (message::$SUCC_CODE, message::$SUCC_UPDATE);
    }

    /**************************************************************************************企业******************************************************************/
    //企业列表
    public function getEnterpriseList(
        \app\service\Publicity             $publicity,
        OrderEnterpriseCertificateRegister $certificateRegister,
        Request                            $request,
        \app\service\Certificate           $certificate,
        SystemCertificate                  $certificateModel,
        OrderEnterpriseExchange            $exchange
    )
    {
        $param = $request->get ();
        $sort = $request->get ('sort') ?: 2;
        $uid = $request->get ('user_login_id');
        if ($sort == 1) {
            $sort = "create_date ASC";
        } else {
            $sort = "create_date DESC";
        }

        /**
         * 上方条件为字符串 高级查询为数组
         * 前期写的时候没有or条件 后期没时间修改
         * 只能model层判断where类型 array使用where查询 string使用whereRaw查询
         */
        $whereOr = '';
        $certificate_leixing = isset($param['condition_leixing'])?explode (',',$param['condition_leixing']):''; //主证书
        $certificate_leibie = isset($param['condition_leibie'])?explode (',',$param['condition_leibie']):'';//证书详细分类
        $seDate = $param['se_date'];

        /**
         * 处理条件
         */
        if ($certificate_leixing && $certificate_leixing[0]){
            foreach ($certificate_leixing as $leixing) {
                /**
                 * 前段传值 *类 正则匹配掉进行查询
                 */
                $leixing = str_replace ('类','',$leixing);

                $cid = $certificateModel->getWhereCertificateIdModel ($leixing);

                if (!$cid){
                    return ReJson (message::$ERROR_CODE,message::$SELECT_CERTIFICATE_ERR);
                }

                if (!$whereOr){
                    $whereOr .= "( certificate_leixing =".$cid;
                }else{
                    $whereOr .= " OR certificate_leixing =".$cid;
                }
            }
            $whereOr.= ')'; //拼接结束
        }
        if ($certificate_leibie && $certificate_leibie[0]){
            foreach ($certificate_leibie as $leibie) {
                /**
                 * 查询是否为组合条件（、）分割
                 */
                if (strpos ($leibie,'、')){
                    $leibieArr = explode ('、',$leibie);
                    $leibielenght = count ($leibieArr);
                    /**
                     * 长度最大为3  1为类别 2为等级 3为专业
                     */
                    if ($leibielenght == 3){
                        //查询证书ID资料
                        $cid = $certificateModel->getWhereCertificateIdModel ($leibieArr[0]);
                        $cid2 = $certificateModel->getWhereCertificateIdModel ($leibieArr[1],$cid);
                        $cid3 = $certificateModel->getWhereCertificateIdModel ($leibieArr[2],$cid2);
                        //判断证书是否存在
                        if (!$cid || !$cid2 || !$cid3){
                            return ReJson (message::$ERROR_CODE,message::$SELECT_CERTIFICATE_ERR);
                        }
                        //拼接SQL条件
                        if (!$whereOr){
                            $whereOr .= " certificate_leibie = ".$cid.' and certificate_dengji = '.$cid2.' and certificate_zhuanye='.$cid3;
                        }else{
                            $whereOr .= " or certificate_leibie =".$cid.' and certificate_dengji = '.$cid2.' and certificate_zhuanye='.$cid3;
                        }
                    }else if ($leibielenght == 2){
                        //查询证书ID资料
                        $cid = $certificateModel->getWhereCertificateIdModel ($leibieArr[0]);
                        $cid2 = $certificateModel->getWhereCertificateIdModel ($leibieArr[1],$cid);
                        //判断证书是否存在
                        if (!$cid || !$cid2 ){
                            return ReJson (message::$ERROR_CODE,message::$SELECT_CERTIFICATE_ERR);
                        }
                        //拼接SQL条件
                        if (!$whereOr){
                            $whereOr .= " certificate_leibie = ".$cid.' and certificate_dengji = '.$cid2;
                        }else{
                            $whereOr .= " or certificate_leibie =".$cid.' and certificate_dengji = '.$cid2;
                        }
                    }else{
                        //查询证书ID资料
                        $cid = $certificateModel->getWhereCertificateIdModel ($leibieArr[0]);
                        //判断证书是否存在
                        if (!$cid){
                            return ReJson (message::$ERROR_CODE,message::$SELECT_CERTIFICATE_ERR);
                        }
                        //拼接SQL条件
                        if (!$whereOr){
                            $whereOr .= " certificate_leibie = ".$cid;
                        }else{
                            $whereOr .= " or certificate_leibie =".$cid;
                        }
                    }
                }else{
                    $cid = $certificateModel->getWhereCertificateIdModel ($leibie);
                    if (!$whereOr){
                        $whereOr .= " certificate_leibie =".$cid;
                    }else{
                        $whereOr .= " or certificate_leibie =".$cid;
                    }
                }
            }
        }

        $whereDate = '';

        if ($seDate == 1){
            $start_create_date = date('Y-m-d').' 00:00:00';
            $end_create_date = date('Y-m-d').' 23:59:59';
            //区间时间
            $whereDate = 'create_date between "'.$start_create_date.'" and "'.$end_create_date.'"';
        }elseif ($seDate == 2){ //近三天
            $start_create_date = date('Y-m-d',time ()-86400*2).' 00:00:00';
            $end_create_date = date('Y-m-d').' 23:59:59';
            //区间时间
            $whereDate = 'create_date between "'.$start_create_date.'" and "'.$end_create_date.'"';
        }elseif ($seDate == 3){//一周
            $start_create_date = date('Y-m-d',time ()-86400*6).' 00:00:00';
            $end_create_date = date('Y-m-d').' 23:59:59';
            //区间时间
            $whereDate = 'create_date between "'.$start_create_date.'" and "'.$end_create_date.'"';
        }elseif ($seDate == 4){//当月
            $start_create_date = date('Y-m-01').' 00:00:00';
            $end_create_date = date('Y-m-d').' 23:59:59';
            //区间时间
            $whereDate = 'create_date between "'.$start_create_date.'" and "'.$end_create_date.'"';
        }

        if(!empty($param['start_date'])){
            $whereDate = '';
        }

        $where = $this->extracted ($request, $certificate, $certificateModel);
        //区间收证价
        if (!empty($param['contract_price_end'])) {
            $where[] = ['price_unit', 'between', [$param['contract_price_start'], $param['contract_price_end']]];
        }


        //人员归属查询
        if (!empty($param['get_uid'])) { //前段传值 搜索用户
            $where[] = ['sale_uid', '=', $param['get_uid']];
        } else {
            //公司
            if (!empty($param['org'])) {
                $userOrganization = new UserOrganization();
                $user = new User();

                //查询这个公司下面所有公司->人员
                $department_id = $request->get ('org');
                if (!$department_id) {
                    ReJson (message::$ERROR_CODE, message::$DEPARTMENT_ID_NULL);
                }
                $department_ids = $userOrganization->getDataRangeDepartmentList ([], $department_id);
                $department_ids[] = (int)$department_id;
                $idArr = $user->getDepartmentUserIdList ($department_ids);

                if (empty($idArr)) {
                    $where[] = ['sale_uid', 'in', 0];
                } else {
                    $where[] = ['sale_uid', 'in', $idArr];
                }
            }
        }
        $list = $certificateRegister->getPublicityListModel ($where, $sort,$whereDate,$whereOr);

        if ($param['cycle'] || $param['cycle'] === 0 || $param['cycle'] === '0') {

            foreach ($list as $k => &$item) {
                if ($item['cycle']['id'] != $param['cycle']) {
                    unset($list[$k]);
                }
            }
        }

        $result = $publicity->setPublicityPersonData ($list, $uid);

        return ReJson (message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $result);
    }

    //新建企业证书倒证
    //同线索库 企业库 新建证书注册

    //删除企业证书
    public function delEnterCertificate(
        Request                            $request,
        OrderEnterpriseCertificateRegister $certificateRegister,
        OrderEnterpriseExchange            $reg,
        SystemOperateLog                   $systemOperateLogModel
    )
    {
        $id = $request->post ('id');
        $uid = $request->post ('user_login_id');
        if (empty($id)) return ReJson (message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        $cerData = $certificateRegister->getWhereIdDataModel ($id);

        //判断当前信息是否为自己提交
//        if ($cerData['get_uid']['id'] != $request->param ('user_login_id')){
//            return ReJson (message::$ERROR_CODE,message::$ERR_NO_POWER_DEL_CAERTIFICATE);
//        }

        //判断当前信息是否有生产数据
        /*   if ($reg->getWhereEnterIdData($id) || $cerData){
               return ReJson (message::$ERROR_CODE,message::$ERR_DELETE_ORDER_EXIST);
           }*/

        $systemOperateLogModel->addOperate ($uid, message::$GSL, '公示栏删除企业证书证书:' . $cerData['certificate_code']);
        $certificateRegister->delIdData (explode (',', $id));

        return ReJson (message::$SUCC_CODE, message::$SUCC_DATELE_DATA);
    }

    //编辑企业证书
    public function editEnterCertificate(
        Request                            $request,
        OrderEnterpriseCertificateRegister $certificateRegister,
        \app\service\Certificate           $certificateSer,
        SystemOperateLog                   $systemOperateLogModel
    )
    {
        $param = $certificateSer->splitCer ($request->post ());
        $uid = $request->post ('user_login_id');

        $param['create_date'] = date ('Y-m-d H:i:s');

        //公示栏与资料部
        $type = explode (',', $param['radio']);

        if (count ($type) == 2) {
            $param['type'] = $type[0] + $type[1];
        } else {
            $param['type'] = $type[0];
        }

        if (empty($param['id'])) return ReJson (message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

        $systemOperateLogModel->addOperate ($uid, message::$GSL, '公示栏编辑企业证书');
        $certificateRegister->editDataModel ($param);

        return ReJson (message::$SUCC_CODE, message::$SUCC_UPDATE);
    }


    //公示栏企业导出企业
    public function PublicityEnterExportExcel(
        Request                            $request,
        Excel                              $excel,
        OrderEnterpriseExchange            $exchange,
        \app\service\Certificate           $certificate,
        SystemCertificate                  $certificateModel,
        \app\service\Publicity             $publicity,
        OrderEnterpriseCertificateRegister $orderEnterpriseCertificateRegister,
        SystemOperateLog                   $systemOperateLogModel
    )
    {
//        $where = $this->extracted ($request, $certificate, $certificateModel);


        $ids = $request->get ('id');
        $uid = $request->get ('user_login_id');

        $data = $orderEnterpriseCertificateRegister->whereIdData ($ids);
        $systemOperateLogModel->addOperate ($uid, message::$GSL, '公示栏导出企业证书');
        $header = [
            ['s_cell' => 'id', 's_value' => '序号', 's_width' => 10],
            ['s_cell' => 'certificate_leixing', 's_value' => '证书类型', 's_width' => 10],
            ['s_cell' => 'certificate_leibie', 's_value' => '证书类别', 's_width' => 10],
            ['s_cell' => 'certificate_dengji', 's_value' => '证书等级', 's_width' => 10],
            ['s_cell' => 'certificate_zhuanye', 's_value' => '证书专业', 's_width' => 10],
            ['s_cell' => 'certificate_b', 's_value' => 'b证', 's_width' => 10],
            ['s_cell' => 'social_security', 's_value' => '社保', 's_width' => 10],
            ['s_cell' => 'project', 's_value' => '项目', 's_width' => 10],

            ['s_cell' => 'cycle', 's_value' => '周期', 's_width' => 10],
//            ['s_cell'=>'transfer','s_value'=>'是否中转','s_width'=>10],
            ['s_cell' => 'price_unit', 's_value' => '单位价', 's_width' => 10],
            ['s_cell' => 'sale_uid', 's_value' => '销售人员', 's_width' => 10],
            ['s_cell' => 'sale_org', 's_value' => '销售部门', 's_width' => 10],
            ['s_cell' => 'people_num', 's_value' => '人数', 's_width' => 10],
            ['s_cell' => 'order_label', 's_value' => '备注', 's_width' => 10],
        ];
        $excel->outExcelStart ($data, $header, '公示栏企业证书导出');

    }

    //公示栏人才导出企业
    public function PublicityPersonExportExcel(
        Request                        $request,
        Excel                          $excel,
        \app\service\Certificate       $certificate,
        SystemCertificate              $certificateModel,
        \app\service\Publicity         $publicity,
        OrderPersonCertificateRegister $personCerReg,
        SystemOperateLog               $systemOperateLogModel
    )
    {
        $uid = $request->param ('user_login_id');

        $idStr = $request->param ('id');
        /**
         * 导出所有数据
         */
//        $where = $this->extracted ($request, $certificate, $certificateModel);
//
//        $gsCertificateData = $publicity->setPublicityPersonData($personCerReg->getWhereStatus(1,1,$where),$uid);
//        $wbCertificateData = $publicity->setPublicityPersonData($personCerReg->getWhereStatus(1,2,$where),$uid);
//
//        $data = array_merge ($wbCertificateData,$gsCertificateData);
//        $arr = [];
//        foreach($data as &$value){
//            $arr[] = $value['arr'];
//        }

        //导出选中id数据
        $arr = $personCerReg->getIdArrDataModel ($idStr);
        $systemOperateLogModel->addOperate ($uid, message::$GSL, '公示栏导出人才证书');

        $header = [
            ['s_cell' => 'id', 's_value' => '序号', 's_width' => 10],
            ['s_cell' => 'certificate_leixing', 's_value' => '证书类型', 's_width' => 10],
            ['s_cell' => 'certificate_leibie', 's_value' => '证书类别', 's_width' => 10],
            ['s_cell' => 'certificate_dengji', 's_value' => '证书等级', 's_width' => 10],
            ['s_cell' => 'certificate_zhuanye', 's_value' => '证书专业', 's_width' => 10],
            ['s_cell' => 'certificate_b', 's_value' => 'b证', 's_width' => 10],
            ['s_cell' => 'social_security', 's_value' => '社保', 's_width' => 10],
            ['s_cell' => 'project', 's_value' => '项目', 's_width' => 10],
            ['s_cell' => 'cycle', 's_value' => '周期', 's_width' => 10],
            ['s_cell' => 'transfer', 's_value' => '是否中转', 's_width' => 10],
            ['s_cell' => 'contract_price', 's_value' => '收证价', 's_width' => 10],
            ['s_cell' => 'get_org', 's_value' => '收证部门', 's_width' => 10],
            ['s_cell' => 'get_uid', 's_value' => '收证人', 's_width' => 10]
        ];
        $excel->outExcelStart ($arr, $header, '公示栏人才导出');
    }


    /**
     * @param \app\Request $request
     * @param \app\service\Certificate $certificate
     * @param \app\model\SystemCertificate $certificateModel
     * @return array|false|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function extracted(Request $request, \app\service\Certificate $certificate, SystemCertificate $certificateModel)
    {

        $certificateSer = new \app\service\Certificate();
        $param = $certificateSer->splitCer ($request->get ());

        //拼接where条件
        $where = [];
        //获取证书条件
        if (isset($param['certificate_id']) & !empty($param['certificate_id'])) {
            if (isset($param['certificate_leixing']) && !empty($param['certificate_leixing'])) {
                $where[] = ['certificate_leixing', '=', (int)$param['certificate_leixing']];
            }
            if (isset($param['certificate_leibie']) && !empty($param['certificate_leibie'])) {
                $where[] = ['certificate_leibie', '=', (int)$param['certificate_leibie']];
            }
            if (isset($param['certificate_dengji']) && !empty($param['certificate_dengji'])) {
                $where[] = ['certificate_dengji', '=', (int)$param['certificate_dengji']];
            }
            if (isset($param['certificate_zhuanye']) && !empty($param['certificate_zhuanye'])) {
                $where[] = ['certificate_zhuanye', '=', (int)$param['certificate_zhuanye']];
            }

        }

        //B证筛选
        if (!empty($param['certificate_b'])) {
            $where[] = ['certificate_b', '=', $param['certificate_b']];
        }


        //社保筛选
        if (!empty($param['social_security'])) {
            $where[] = ['social_security', '=', $param['social_security']];
        }

        //项目筛选
        if (!empty($param['project'])) {
            $where[] = ['project', '=', $param['project']];
        }

        //是否中转筛选
        if (!empty($param['transfer'])) {
            if ($param['transfer'] == 999) { //为了搜索0值
                $where[] = ['transfer', '=', 0];
            } else {
                $where[] = ['transfer', '=', $param['transfer']];
            }
        }

        //区间时间 se_date 当天 当月 近三天 为未选择
        if (!empty($param['start_date']) && empty($param['se_date'])) {

            $arr = explode (',', $param['start_date']);
            if (count ($arr) != 2) return ReJson (message::$ERROR_CODE, message::$ERR_PARAM_EMPTY);

            $where[] = ['create_date', 'between', [$arr[0] . ' 00:00:00', $arr[1] . ' 23:59:58']];
        }
        return $where;
    }

    /**
     * 公示栏滚动规则设置
     */
    public function setPublicRollRule(Request $request,SystemOperateLog $systemOperateLogModel,User $userModel)
    {
        $uid = $request->post ('user_login_id');
        $nickName = $userModel->getIdNickName ($uid);
        $param = $request->post ();

        if (!$param['type']) return ReJson (message::$ERROR_CODE,message::$ERR_PARAM_EMPTY);

        if(!$param['value']){
            $param['value'] = 0;
        }

        $rule = Db::table('public_roll_rule')->where('type',$param['type'])->value ('value');

        if (!$rule){
            Db::table('public_roll_rule')->insert ([
                'type'=>$param['type'],
                'value'=>$param['value'],
                'uid'=>$uid,
                'create_date'=>date('Y-m-d H:i:s')
            ]);
        }

        Db::table('public_roll_rule')->where('type',$param['type'])->update ([
            'value'=>$param['value'],
            'uid'=>$uid
        ]);

        /**
         * 添加日志
         */
        if ($param['type'] == 1){
            $type = '人才';
        }else{
            $type = '企业';
        }
        if ($param['value'] == 1){
            $value = '当日';
        }elseif($param['value'] == 2){
            $value = '近三天';
        }elseif($param['value'] == 3){
            $value = '本周';
        }elseif($param['value'] == 4){
            $value = '本月';
        }else{
            $value = '全部';
        }
        $systemOperateLogModel->addOperate ($uid,message::$GSL,'用户：'.$nickName.'添加公示栏'.$type.'滚动规则为：'.$value);
        return ReJson (message::$SUCC_CODE,message::$SUCC_SETTING);
    }

    /**
     * 公示栏滚动规则获取
     */
    public function getPublicRollRule(Request $request)
    {
        $uid = $request->get ('user_login_id');
        $param = $request->get ();

        if (!$param['type'] ) return ReJson (message::$ERROR_CODE,message::$ERR_PARAM_EMPTY);

        $rule = Db::table('public_roll_rule')->where('type',$param['type'])->value ('value');
        if (!$rule){
            $rule = 0;
        }

        return ReJson (message::$SUCC_CODE,message::$SUCC_SELECT_DATA,$rule);
    }
}